﻿using CIS.Web.Common;
using CIS.Web.Models;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ProfileQuiz")]
	public class ProfileQuizController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ProfileQuizModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = from profileQuizInfo in DbContext.ProfileQuizInfo.AsNoTracking()
					.Where(x => x.UserName == LoginUser.UserName)
				  join quizMaster in DbContext.QuizMaster.AsNoTracking()
					on profileQuizInfo.QuizId equals quizMaster.ID into quizs
				  from quiz in quizs.DefaultIfEmpty()
				  join conferenceMaster in DbContext.ConferenceMaster.AsNoTracking()
					on quiz.ConferenceId equals conferenceMaster.ID
				  select new
				  {
					  quizName = quiz.QuizName,
					  conferenceName = conferenceMaster.ConferenceName,
					  updateDate = profileQuizInfo.UpdateDate,
					  status = profileQuizInfo.Status,
					  quizId = profileQuizInfo.QuizId,
					  ConferenceNickName = conferenceMaster.ConferenceNickName,
					  HomePageUrl = conferenceMaster.HomePageUrl,
					  IsInternational = conferenceMaster.IsInternational,
					  CreateDate = profileQuizInfo.CreateDate,
				  };

			if (!string.IsNullOrWhiteSpace(model.queryConferenceName) && model.queryConferenceName != "")
			{
				sql = sql.Where(x => x.conferenceName.Contains(model.queryConferenceName));
			}
			if (!string.IsNullOrWhiteSpace(model.queryHasReply) && model.queryHasReply != "")
			{
				sql = sql.Where(x => x.status.Contains(model.queryHasReply));
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.CreateDate).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				quizName = x.quizName,
				conferenceName = x.conferenceName,
				status = x.status,
				updateDate = x.updateDate == null ? (ConstValues.strHyphen + ConstValues.strHyphen) : (!x.IsInternational ? x.updateDate.Value.ToString("yyyy-MM-dd") : x.updateDate.Value.ToString("MM/dd/yyyy")),
				quizId = x.quizId,
				ConferenceNickName = x.ConferenceNickName,
				HomePageUrl = x.HomePageUrl
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}
	}
}